# -*- coding: UTF-8 -*-
__author__ = 'chzhu'

from Database import Proxy, Cookie
from Config import Config
from Logger import Logger
import urllib2

class Opener(object):
    def __init__(self):
        # self.proxy = Proxy.randOne()
        self.cookie = Cookie.randOne()

        # proxy_handler = urllib2.ProxyHandler({"http" : self.proxy.host})

        # self.opener = urllib2.build_opener(proxy_handler)

        self.opener = urllib2.build_opener()

        self.headers = {'cookie': self.cookie.value}

    def urlOpen(self, url):
        req = urllib2.Request(url, headers=self.headers)

        while True:
            try:
                html = self.opener.open(req, timeout=Config.timeout).read()
                if html is None:
                    continue

                return html
            except Exception as e:
                Logger.logger.debug(e)

    def report(self):
        self.proxy.report()
        self.cookie.report()
